// miniprogram/pages/historyRecord/historyRecord.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    records: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getRecords()
  },

  /**
   * 获取记录
   */
  getRecords:function(e){
    var that = this;
    if (wx.getStorageSync('openid')){
      wx.showLoading({
        title: '',
      })
      wx.cloud.callFunction({
        name: 'getRecords',
        data: {
          userid: wx.getStorageSync('openid')
        },
        success: res => {
          console.log('[云函数] [getRecords] 调用成功: ', res.result.data)
          wx.hideLoading()
          that.setData({
            records: res.result.data
          })
        },
        fail: err => {
          console.error('[云函数] [getRecords] 调用失败', err)
        }
      })
    }
  },

  /**
   * 修改
   */
  clickEdit: function(e) {
    wx.navigateTo({
      url: '../updateRecord/updateRecord?record=' + JSON.stringify(e.currentTarget.dataset.record),
    })
  },

  /**
   * 删除
   */
  clickDelete: function(e) {
    var that = this;
    wx.showModal({
      title: '删除后无法恢复',
      content: '确定删除？',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '',
          })
          wx.cloud.callFunction({
            name: 'deleteRecord',
            data: {
              recordid: e.currentTarget.dataset.recordid
            },
            success: res => {
              console.log('[云函数] [deleteRecord] 调用成功: ', res.result.stats.removed)
              if (res.result.stats.removed == 1) {
                wx.hideLoading()
                wx.showToast({
                  title: '删除成功',
                  success(res) {
                    setTimeout(function () {
                      that.getRecords()
                    }, 1000)
                  }
                })
              }
            },
            fail: err => {
              console.error('[云函数] [deleteRecord] 调用失败', err)
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
})